<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\circle\Rult;
use app\common\model\Trends;
use app\common\model\Wxlogin;
use app\common\model\Rultlog;
use fast\Http;
use think\Config;
use think\Db;

/**
 * 消息群发接口
 */
class Send extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

	//群发消息
	public function index() {
		set_time_limit(0);
		ini_set('memory_limit', '-1');
		$wxip = Config::get("site2.wxip");//IP
		$rult = Rult::where(['send_time'=>array("elt",time())])->select();
		foreach($rult as $value){
			//判断微信是否登录
			$response = Http::post($wxip.$value->port.'/IsLoginStatus', json_encode([]));
			//如果未登录不发送消息
			if($response){
				$res = json_decode($response, true);
				if($res['onlinestatus'] == 3 && time() >= $value->send_time ){//如果
					//筛选动态信息
					$where = [];
					$where['state'] = 1;
					$where['is_see'] = 1;
					$where['is_draft'] = 2;
					$where['circle_id'] = $value->circle_id;
					if(!empty($value->cate_ids)){
						$where['cate_id'] = array("in",$value->cate_ids);
					}
					$list = Trends::where($where)->order('create_time asc')->paginate($value->send_num, false, ["page" => $value->page]);
					//print_r($list);
					$page = $value->page + 1;
					if(count($list) > 0) {
						if(count($list) < $value->send_num){
							$page = $page - 1;
						}
						$str = "";
						foreach ($list as $k => $v) {
							//判断是否发送过
							$wxlog = Db::connect('database.db_second')->name("wxlog")->where(['rult_id'=>$value->id,"trends_id"=>$v->id])->find();
							if(!$wxlog){
								$str .= $v->title."：".link_url($v->id)."\n";
								Db::connect('database.db_second')->name("wxlog")->insert(['title'=>$v->title,'rult_id'=>$value->id,"trends_id"=>$v->id]);
							}else{
								$str .= "";
							}
						}

						if($str){
							$sendList = explode(',',$value->crowd);
							foreach ($sendList as $v) {
								//请求第三方接口发送消息
								$queryarr = [
									"wxid" => $v,
									//"crowd"=>$value->crowd,
									"msg"  => $str . $value->url_name ." ".$value->url_web." ".$value->url_content
								];
								//发送消息
								sleep(1);//延迟1秒
								$response = Http::post($wxip . $value->port . '/SendTextMsg', json_encode($queryarr));
							}
						}
						//发送成功后记录发送时间
						$value->save(['page' => $page, 'send_time' => time() + ($value->send_min * 60)]);
						Rultlog::insert(['day'=>date("Y-m-d H:i:s"),'title'=>'成功','rult_id'=>$value->id]);
					}
					Rultlog::insert(['day'=>date("Y-m-d H:i:s"),'title'=>'失败2','rult_id'=>$value->id]);
				}
			}else{
				//Db::name('rultlog')->insert(['day'=>date("Y-m-d H:i:s"),'title'=>'失败','rult_id'=>$value->id]);
			}
		}
	}
}
